package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.util.ByteUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 统计指定时间区间内的营业额数据
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //创建存储日期的数据 eg：2022-10-01,2022-10-02,2022-10-03
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //select sum(amount) from orders where order_time <=  endTime and order_time >= beginTime and status = 5
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;

            turnoverList.add(turnover);

        }


        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ','))
                .turnoverList(StringUtils.join(turnoverList, ','))
                .build();
    }

    /**
     * 统计指定时间区间内的用户统计数据
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Long> totalUserList = new ArrayList<>();
        List<Long> newUserList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //select count(id) from user where create_time > ?
            Map map = new HashMap();
            map.put("endTime", endTime);
            Long totalUserNumber = userMapper.countByMap(map);
            //select count(id) from user where create_time >= beginTime and create_time <= endTime
//            Map newUserMap = new HashMap();
            map.put("beginTime", beginTime);
//            newUserMap.put("endTime", endTime);
            Long newUserNumber = userMapper.countByMap(map);
            newUserNumber = newUserNumber == null ? 0 : newUserNumber;
            totalUserNumber = totalUserNumber == null ? 0 : totalUserNumber;

            totalUserList.add(totalUserNumber);
            newUserList.add(newUserNumber);

        }


        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList, ','))
                .newUserList(StringUtils.join(newUserList, ','))
                .totalUserList(StringUtils.join(totalUserList, ','))
                .build();
    }

    /**
     * 统计指定时间区间内的订单数据
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
//        Integer totalOrderCount = 0;
//        Integer totalValidOrderCount = 0;


        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //每日订单数
            //select count(id) from orders where order_time <= endTime and order_time >= beginTime

            Integer orderCount = getOrderCount(beginTime, endTime, null);
//            totalOrderCount += orderCount;
            orderCountList.add(orderCount);

            //每日有效订单数
            //select count(id) from orders where order_time <= endTime and order_time >= beginTime and status = 5
//            Map validOrderCountMap = new HashMap();
//            validOrderCountMap.put("beginTime", beginTime);
//            validOrderCountMap.put("endTime", endTime);

            Integer validOrderCount = getOrderCount(beginTime, endTime, Orders.COMPLETED);
//            totalValidOrderCount += validOrderCount;
            validOrderCountList.add(validOrderCount);


        }
        //计算时间区间内订单总数
        Integer totalValidOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();


        //计算时间区间内有效订单总数
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = totalValidOrderCount / totalOrderCount.doubleValue();
        }


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList, ','))
                .orderCountList(StringUtils.join(orderCountList, ','))
                .validOrderCountList(StringUtils.join(validOrderCountList, ','))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(totalValidOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    private Integer getOrderCount(LocalDateTime beginTime, LocalDateTime endTime, Integer status) {
        Map map = new HashMap();
        map.put("beginTime", beginTime);
        map.put("endTime", endTime);
        map.put("status", status);

        return orderMapper.countByMap(map);
    }

//    /**
//     * 查询销量排名top10接口
//     *方法一（自己写的）
//     * @param begin
//     * @param end
//     * @return
//     */
//    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
//        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
//        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
//        //查询时间区间内所有的订单号
//        //select id from orders where order_time >= begin and order_time <= end and status = 5
//        Map map = new HashMap();
//        map.put("beginTime", beginTime);
//        map.put("endTime", endTime);
//        map.put("status", Orders.COMPLETED);
//
//        List<Integer> ids = orderMapper.getIdsByMap(map);
//
////        log.info("ids:{}",ids.toString());
//
//        //查询符合条件的菜品名称，数量 进行排名
//        Map orderDetailMap = new HashMap();
//        orderDetailMap.put("orderIds", ids);
//        //语句一，多表联查
//        //select od.name,sum(od.number) number from order_detail od,orders o
//        // where o.id = od.order_id and status = 5
//        //and o.order_time > ? and o.order_time < ?
//        // group by od.dish_id
//        // order by od.number desc
//        // limit 0,10
//
//        //select name,sum(number) number from order_detail where order_id in (72,73,74,75,76)  group by dish_id order by number desc
//        List<OrderDetail> orderDetailList = orderDetailMapper.getByMap(orderDetailMap);
//        log.info("subOrderDetails:{}", orderDetailList);
//        List<String> nameList = new ArrayList();
//        List<String> numberList = new ArrayList();
//        for (OrderDetail orderDetail : orderDetailList) {
//            nameList.add(orderDetail.getName());
//            numberList.add(orderDetail.getNumber().toString());
//        }
//
//
//        return SalesTop10ReportVO.builder()
//                .nameList(StringUtils.join(nameList, ','))
//                .numberList(StringUtils.join(numberList, ','))
//                .build();
//    }

    /**
     * 查询销量排名top10接口
     * 方法二（视频教的，比较简洁）
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        String nameList = StringUtils.join(names, ',');

        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        String numberList = StringUtils.join(numbers, ',');

        return SalesTop10ReportVO
                .builder()
                .numberList(numberList)
                .nameList(nameList)
                .build();

    }

    /**
     * 导出运营数据报表
     *
     * @param response
     */
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库，获取营业数据----查询最近30天的运营数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        LocalDateTime dateBeginTime = LocalDateTime.of(dateBegin, LocalTime.MIN);
        LocalDateTime dateEndTime = LocalDateTime.of(dateEnd, LocalTime.MAX);

        BusinessDataVO businessDataVO = workspaceService.getBusinessData(dateBeginTime, dateEndTime);


        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
//        log.info(inputStream.toString());
        try {
            //2.通过POI将数据写入到Excel文件中
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = excel.getSheetAt(0);
            sheet.getRow(1).getCell(1).setCellValue("时间：" + dateBegin + "至" + dateEnd);

            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessDataVO.getTurnover());
            row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO.getUnitPrice());


//            //方法一
////            //明细数据
////            Integer rowNum = 7;
////            while (!dateBegin.equals(dateEnd.plusDays(1))) {
////                //查询某一天的营业数据
////                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateBegin, LocalTime.MAX));
////                row = sheet.getRow(rowNum);
////                row.getCell(1).setCellValue(dateBegin.toString());
////                row.getCell(2).setCellValue(businessData.getTurnover());
////                row.getCell(3).setCellValue(businessData.getValidOrderCount());
////                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
////                row.getCell(5).setCellValue(businessData.getUnitPrice());
////                row.getCell(6).setCellValue(businessData.getNewUsers());
////                rowNum = rowNum + 1;
////                dateBegin = dateBegin.plusDays(1);
////            }

            //方法二
            for (int i = 0; i < 30; i++) {

                LocalDate date = dateBegin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                //获得某一行
                row = sheet.getRow(i + 7);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }


            //3.通过输出流将Excel文件下载到客户端浏览器
            OutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            //关闭资源
            excel.close();
            outputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }


}
